package com.ilink.teacherservice.service.tingwu;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class FileUploadService {

    @Autowired
    private RestTemplate restTemplate;

    public String id_return(File file, String apiKey) throws Exception {
        // 目标URL
        String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/files";

        // 设置Authorization头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization", "Bearer " + apiKey);

        // 创建 MultiValueMap 以包含文件和其他参数
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(file));
        body.add("purpose", "file-extract");

        // 创建 HttpEntity 包含请求头和请求体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送 POST 请求并获取响应
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 获取响应体内容
        String result = response.getBody();

        // 创建 ObjectMapper 实例
        ObjectMapper mapper = new ObjectMapper();

        // 将 JSON 字符串转换为 Map，使用 TypeReference 来指定类型
        Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {});

        String id=map.get("id").toString();
        return id;

    }
}
